#!/bin/bash

set -e

cd "$(dirname "$0")/.."

function clone_repo {
  owner=$1
  name=$2
  sha=$3

  path=examples/$name
  if [ ! -d "$path" ]; then
    echo "Cloning $owner/$name"
    git clone "https://github.com/$owner/$name" "$path"
  fi

  pushd "$path" > /dev/null
  head=$(git rev-parse HEAD)
  if [ "$head" != "$sha"  ]; then
    echo "Updating $owner/$name from $head to $sha"
    git fetch
    git reset --hard $sha
  fi
  popd > /dev/null
}

clone_repo 0install 0install b88111c7dc1612b0beaa175df9c91df4fa36556b
clone_repo BinaryAnalysisPlatform bap a972f8a419294dfb21847db5172ba58c5d7767eb
clone_repo dbuenzli cmdliner 2c370b7ca519473584c04a3c4f89683f3cc0aad0
clone_repo facebook flow 5ada26749e0a95a1e562aee955859cc10decf517
clone_repo facebook pyre-check b794d924f77dd005af15da6fafb73010394804e3
clone_repo garrigue lablgtk b298ee1b4cba588537df1c4cfd996358e3a8750b
clone_repo janestreet base 8993e35ba2e83e5020b2deb548253ef1e4a699d4
clone_repo mirage ocaml-cohttp 628d8716b22bb7933863dd584673745c974707be
clone_repo ocaml dune 50815dbdda5c924142bf2c54feba87c5894465d5
clone_repo ocaml merlin dd7663fcff929ac395909cada9e829acdc77e97e
clone_repo ocaml ocaml 1042d5cd441ec2c8b5c87151313dbe7d1eebf2e7
clone_repo ocaml opam 51d458b5946d938aa2b45ddc924a2ad75130fb69
clone_repo ocaml-ppx ocamlformat b436f8d9e53661c1f5b51d40f701b9bd74cd4f84
clone_repo ocaml-ppx ppxlib 5fe8514d59ccbdd312b709ed3aea00781feefca3
clone_repo ocsigen js_of_ocaml ee5c335882aab362e66f5993d2a97bf7886cd247
clone_repo ocsigen lwt b3e7dd029dacbe37df9565c142c2206cfe6831c2
clone_repo owlbarn owl eead31f1920e63b876421e6a30e61c947f29827f

known_failures="$(cat script/known_failures.txt)"

tree-sitter parse -q \
  'examples/**/*.ml' \
  'examples/**/*.mli' \
  $(for failure in $known_failures; do echo "!${failure}"; done)

example_count=$(find examples -name '*.ml' -o -name '*.mli' | wc -l)
failure_count=$(wc -w <<< "$known_failures")
success_count=$(( $example_count - $failure_count ))
success_percent=$(bc -l <<< "100*${success_count}/${example_count}")

printf \
  "Successfully parsed %d of %d example files (%.1f%%)\n" \
  $success_count $example_count $success_percent
